package com.eduagent.xwqeduagent.exception;


import com.eduagent.xwqeduagent.api.speechsynthesis.api.exception.SpeechSynthesisException;
import com.eduagent.xwqeduagent.api.speechsynthesis.api.model.ErrorResponse;
import com.eduagent.xwqeduagent.common.BaseResponse;
import com.eduagent.xwqeduagent.common.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.UUID;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public BaseResponse<?> businessExceptionHandler(BusinessException e) {
        log.error("BusinessException", e);
        return ResultUtils.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
        log.error("RuntimeException", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统错误");
    }
    
    /**
     * 处理语音合成服务异常
     */
    @ExceptionHandler(SpeechSynthesisException.class)
    public ResponseEntity<ErrorResponse> handleSpeechSynthesisException(SpeechSynthesisException ex) {
        log.error("语音合成服务异常: {}", ex.getMessage(), ex);
        
        ErrorResponse errorResponse = ErrorResponse.create(
                ex.getErrorCode(), 
                ex.getSid() != null ? ex.getSid() : generateSpeechSid(),
                ex.getDetail()
        );
        
        return new ResponseEntity<>(errorResponse, HttpStatus.OK);
    }
    
    /**
     * 处理语音合成参数验证异常
     */
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    public Object handleValidationException(Exception ex) {
        log.error("参数验证异常: {}", ex.getMessage());
        
        // 如果是来自语音合成API的请求，返回特定格式的响应
        if (isFromSpeechSynthesisApi()) {
            ErrorResponse errorResponse = ErrorResponse.create(
                    com.eduagent.xwqeduagent.api.speechsynthesis.api.constant.ErrorCode.PARAMETER_VALIDATION_FAILED,
                    generateSpeechSid(),
                    ex.getMessage()
            );
            return new ResponseEntity<>(errorResponse, HttpStatus.OK);
        }
        
        // 对于其他请求，使用通用错误响应格式
        return ResultUtils.error(ErrorCode.PARAMS_ERROR, ex.getMessage());
    }
    
    /**
     * 处理请求体解析异常
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Object handleMessageNotReadableException(HttpMessageNotReadableException ex) {
        log.error("请求体解析异常: {}", ex.getMessage());
        
        // 如果是来自语音合成API的请求，返回特定格式的响应
        if (isFromSpeechSynthesisApi()) {
            ErrorResponse errorResponse = ErrorResponse.create(
                    com.eduagent.xwqeduagent.api.speechsynthesis.api.constant.ErrorCode.REQUEST_FORMAT_INVALID,
                    generateSpeechSid()
            );
            return new ResponseEntity<>(errorResponse, HttpStatus.OK);
        }
        
        // 对于其他请求，使用通用错误响应格式
        return ResultUtils.error(ErrorCode.PARAMS_ERROR, "请求格式错误");
    }
    
    /**
     * 检查请求是否来自语音合成API
     */
    private boolean isFromSpeechSynthesisApi() {
        try {
            String requestUri = org.springframework.web.context.request.RequestContextHolder
                    .currentRequestAttributes()
                    .getAttribute("javax.servlet.forward.request_uri", 
                            org.springframework.web.context.request.RequestAttributes.SCOPE_REQUEST)
                    .toString();
            return requestUri != null && requestUri.startsWith("/api/speech");
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 生成会话ID
     */
    private String generateSpeechSid() {
        return "speech" + UUID.randomUUID().toString().replace("-", "");
    }
}